package Demo2;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-03-07
 * Time: 16:13
 */


class Student implements Comparable<Student> {
    public String name;
    public int age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }


    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }
}

class AgeComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

class NameComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);//字符使用compareTo()
    }
}


public class Test2 {


    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("hello", 10);
        students[1] = new Student("bit", 11);
        students[2] = new Student("abc", 3);
        System.out.println(Arrays.toString(students));

        //根据姓名排序
        /*NameComparator nameComparator = new NameComparator();
        Arrays.sort(students, nameComparator);
        System.out.println(Arrays.toString(students));*/
        AgeComparator ageComparator = new AgeComparator();
        Arrays.sort(students, ageComparator);
        System.out.println(Arrays.toString(students));


    }

    public static void main1(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("hello", 10);
        students[1] = new Student("bit", 11);
        students[2] = new Student("abc", 3);
        System.out.println(Arrays.toString(students));
        Arrays.sort(students);
        System.out.println(Arrays.toString(students));
    }
}
